package com.yyfax.infrastructure.base;

import android.app.Application;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.util.DisplayMetrics;
import android.widget.Toast;

import com.yyfax.common.CLog;
import com.yyfax.infrastructure.network.NetworkReceiver;

import java.util.Locale;

/**
 * Created by HenryZhang on 16-10-27.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 */
public class BaseApplication<T extends BaseApplication> extends Application {
	private static final String TAG = "BaseApplication";

	/**
	 * default value is base on 480*800 4.0inch screen
	 */
	public static int densityDpi = 240;
	public static float density = 1.5f;//scale
	public static float scaledDensity = 1.5f;//font scale
	public static int widthPixels = 480;
	public static int heightPixels = 800;
	public static float xDpi = 240.0f;
	public static float yDpi = 240.0f;

	public static String versionName;
	public static int versionCode;
	public static String channel = "";

	private static int mMainThreadId;
	private static Handler mMainThreadHandler;

//	public void getVersion() {
//		try {
//			PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
//			CLog.e(TAG, "!@#$#$%^$%&%*^&(&)" + pi.versionName);
//		} catch (PackageManager.NameNotFoundException e) {}
//	}

	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		MultiDex.install(this);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		mMainThreadId = android.os.Process.myTid();
		CLog.e(TAG, "onCreate: uid=" + android.os.Process.myUid() +
				", supportsProcesses=" + android.os.Process.supportsProcesses() +
				", pid=" + android.os.Process.myPid() +
				", tid=" + mMainThreadId);
		mMainThreadHandler = new Handler();
		getDisplayMetrics();
		getPackageInfo();

		NetworkReceiver nr = new NetworkReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(nr, filter);

//		getPref();
	}

	public static boolean isRunInMainThread() {
		return android.os.Process.myTid() == mMainThreadId;
	}

	private void getDisplayMetrics() {
		DisplayMetrics dm = CUtility.getDisplayMetrics(this);
		densityDpi = dm.densityDpi;
		density = dm.density;
		scaledDensity = dm.scaledDensity;
		widthPixels = dm.widthPixels;
		heightPixels = dm.heightPixels;
		xDpi = dm.xdpi;
		yDpi = dm.ydpi;

		String desc = "densityDpi = " + densityDpi + ", scale = " + density + "; fontScale = " + scaledDensity + "; " + widthPixels + "*" + heightPixels + "; " + xDpi + "*" + yDpi;
		CLog.i(TAG, desc);
	}

	private void getPackageInfo() {
		try {
			PackageManager pm = getPackageManager();
			PackageInfo pi = pm.getPackageInfo(getPackageName(), 0);
			versionName = pi.versionName;
			if (versionName == null || versionName.length() <= 0) {
				versionName = "1.0.0";
			}

			versionCode = pi.versionCode;
			if (versionCode == -1) {
				versionCode = 0;
			}
			ApplicationInfo appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
			channel = appInfo.metaData.getString("UMENG_CHANNEL");
			CLog.i(TAG, "获取channel=" + channel + ";versionCode=" + versionCode + "'versionName=" + versionName);
		} catch (Exception e) {
			versionName = "1.0.0";
			versionCode = 0;
			channel = "";
		}
	}

	/**
	 * 返回的是dp为单位的值
	 */
	public static int fromXHDPItoDeviceScale(int dp) {
		return ((int) ((dp / 3) * density));
	}

//	/**
//	 * Support basic data types and JSONObject, JSONArray
//	 */
//	private SharedPreferences mSharedPref;
//	private SharedPreferences.Editor mSharedPrefEditor;
//
//	/**
//	 * 源码发现android会在新线程里打开shared preference
//	 */
//	public SharedPreferences getPref() {
//		if (mSharedPref == null) {
//			synchronized (BaseApplication.class) {
//				if (mSharedPref == null) {
//					final String fileName = getPackageName() + ".xml";
//					try {
//						mSharedPref = new SecuredPreference(this, "", fileName);
//					} catch (Exception e) {
//						mSharedPref = SecuredPreference.useAndroidSharedPreference(this, fileName);
//					}
//				}
//			}
//		}
//		return mSharedPref;
//	}
//
//	public synchronized SharedPreferences.Editor getPrefEditor() {
//		if (mSharedPrefEditor == null) {
//			SharedPreferences sp = getPref();
//			mSharedPrefEditor = sp.edit();
//		}
//		return mSharedPrefEditor;
//	}
//
//	/**Support basic data types and JSONObject, JSONArray*/
//	public void savePreference(String key, Object value) {
//		if (value == null) return;
//		SharedPreferences.Editor e = getPrefEditor();
//		if (value instanceof String) {
//			e.putString(key, (String) value);
//		} else if (value instanceof Long) {
//			e.putLong(key, (Long) value);
//		} else if (value instanceof Integer) {
//			e.putInt(key, (Integer) value);
//		} else if (value instanceof Boolean) {
//			e.putBoolean(key, (Boolean) value);
//		} else if (value instanceof Float) {
//			e.putFloat(key, (Float) value);
//		} else if(value instanceof JSONObject) {
//			e.putString(key, value.toString());
//		} else if (value instanceof JSONArray) {
//			e.putString(key, value.toString());
//		} else {
//			e.putString(key, value.toString());
//		}
//		e.apply();
//	}
//
//	public Object readPreference(String key) {
//		SharedPreferences sp = getPref();
//		Map<String, ?> map = sp.getAll();
//		if (map != null && map.containsKey(key)) {
//			return map.get(key);
//		}
//		return null;
//	}
//
//	public void removePreference(String key) {
//		SharedPreferences.Editor editor = getPref().edit();
//		editor.remove(key);
//		editor.apply();
//	}
//
//	public boolean readBoolean(String key, boolean defaultValue) {
//		SharedPreferences sp = getPref();
//		return sp.getBoolean(key, defaultValue);
//	}
//
//	public String readString(String key, String defaultValue) {
//		SharedPreferences sp = getPref();
//		return sp.getString(key, defaultValue);
//	}
//
//	public int readInt(String key, int defaultValue) {
//		SharedPreferences sp = getPref();
//		return sp.getInt(key, defaultValue);
//	}
//
//	public void saveNetResponse(String url, Object response) {
//		String md5 = MD5.getMD5(url);
//		savePreference(md5, response);
//	}
//
//	public String readNetResponse(String url) {
//		String md5 = MD5.getMD5(url);
//		Object obj = readPreference(md5);
//		if (obj != null)
//			return obj.toString();
//		return null;
//	}

	public void cancelRequest(String tag) {

	}

	public String formatString(String format, Object... args) {
		return String.format(Locale.US, format, args);
	}

	/**
	 * use handler post runnable on main thread
	 */
	public static boolean post(Runnable runnable) {
		return mMainThreadHandler.post(runnable);
	}

	private static void toast(String message) {
		Toast.makeText(getInstance(), message, Toast.LENGTH_LONG).show();
	}

	/**
	 * show toast in main thread
	 */
	public static void toastSafe(final String message) {
		if (isRunInMainThread()) {
			toast(message);
		} else {
			post(new Runnable() {
				@Override
				public void run() {
					toast(message);
				}
			});
		}
	}

	public int getResourceColor(int colorRes) {
		return getResources().getColor(colorRes);
	}

	public static BaseApplication getInstance() {
		CLog.e(TAG, "warning: getInstance() is going to new a BaseApplication instance");
		return new BaseApplication();//todo
	}
}
